package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"reflect"

	"github.com/gorilla/mux"

	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
	core_auth "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/region"
	iotda "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/iotda/v5"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/iotda/v5/model"
)

var (
	projectID = "1c9e96c956ea427ab24de604056b2785"
	endpoint  = "f14da37201.st1.iotda-app.cn-north-4.myhuaweicloud.com"
	regionID  = "cn-north-4"
	deviceID  = "686f6015d582f2001839e970_test1"
	ak        = "HPUA19FC6JTVTCMPNGLS"
	sk        = "p8mlhyjCw36OT3Xkfrc6QW4HDYPH4Yp5wvkPOmnW"
)

func stringPtr(s string) *string {
	return &s
}

func extractProperties(props *model.DeviceShadowProperties) map[string]interface{} {
	result := make(map[string]interface{})
	if props == nil {
		return result
	}

	v := reflect.ValueOf(props).Elem()
	t := v.Type()
	for i := 0; i < v.NumField(); i++ {
		field := v.Field(i)
		fieldType := t.Field(i)
		if !field.IsNil() {
			result[fieldType.Name] = field.Elem().Interface()
		}
	}
	return result
}

func getShadow() (map[string]interface{}, error) {
	auth := basic.NewCredentialsBuilder().
		WithAk(ak).
		WithSk(sk).
		WithProjectId(projectID).
		WithDerivedPredicate(core_auth.GetDefaultDerivedPredicate()).
		Build()

	client := iotda.NewIoTDAClient(
		iotda.IoTDAClientBuilder().
			WithRegion(region.NewRegion(regionID, endpoint)).
			WithCredential(auth).
			Build(),
	)

	req := &model.ShowDeviceShadowRequest{
		DeviceId:   deviceID,
		InstanceId: stringPtr(""),
	}

	resp, err := client.ShowDeviceShadow(req)
	if err != nil {
		return nil, err
	}

	props := make(map[string]interface{})
	for _, shadow := range *resp.Shadow {
		if shadow.Reported != nil {
			m := extractProperties(shadow.Reported)
			for k, v := range m {
				props[k] = v
			}
		}
	}
	return props, nil
}

//添加 CORS 支持
func withCORS(handler http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// 添加跨域头
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

		// 对于预检请求直接返回
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusOK)
			return
		}

		handler(w, r)
	}
}

func shadowHandler(w http.ResponseWriter, r *http.Request) {
	properties, err := getShadow()
	if err != nil {
		http.Error(w, fmt.Sprintf("获取失败: %v", err), http.StatusInternalServerError)
		return
	}

	resp := map[string]interface{}{
		"device_id":  deviceID,
		"properties": properties,
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(resp)
}

func registerShadowRoutes(r *mux.Router) {
	r.HandleFunc("/device/shadow", withCORS(shadowHandler)).Methods("GET", "OPTIONS")
}
